home *** CD-ROM | disk | FTP | other *** search
/ CD Actual 9 / CDACTUAL9.iso / share / Dos / VARIOS / pascal / DELPHI.SWG / 0036_Creating and Using Parameterized Queries.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  1996-02-21  |  1.9 KB  |  76 lines

  1.  
  2. Q:  How do I pass a variable to a query?
  3.  
  4. A:  First, you must write a query that uses a variable.
  5.  
  6. Select Test."FName", Test."Salary Of Employee"
  7. From Test
  8. Where Test."Salary of Employee" > :val
  9.  
  10. Note:  If you just write the field name as 
  11. "Salary of Employee" you will get a Capability Not
  12. Supported error.  It must be Test."Salary of Employee".
  13.  
  14. In this can the variable name is "val", but it can be whatever 
  15. you want (of course).  Then, you go to the TQuery's params 
  16. property and set the "val" parameter to whatever the 
  17. appropriate type is. In our example here we will call it an 
  18. integer.
  19.  
  20. Next, you write the code that sets the parameter's value.  
  21. We will be setting the value from a TEdit box.
  22.  
  23. procedure TForm1.Button1Click(Sender: TObject);
  24. begin
  25.   with Query1 do
  26.   begin
  27.     Close;
  28.     ParamByName('val').AsInteger := StrToInt(Edit1.Text);
  29.     Open;
  30.   end;
  31. end;
  32.  
  33.  
  34. Note:  you may want to place this code in a try..except 
  35. block as a safety precaution.
  36.  
  37. If you want to use a LIKE in your query, you can do
  38. it this way:
  39.  
  40. Note:  This next section uses the customer table from
  41. the \delphi\demos\data directory.  It can also be 
  42. referenced by using the DBDEMOS alias.
  43.  
  44. SQL code within the TQuery.SQL property:
  45.  
  46.   SELECT * FROM CUSTOMER
  47.   WHERE Company LIKE :CompanyName
  48.  
  49.  
  50. Delphi code:
  51.  
  52. procedure TForm1.Button1Click(Sender: TObject);
  53. begin
  54.   with Query1 do
  55.   begin
  56.     Close;
  57.     ParamByName('CompanyName').AsString := Edit1.Text + '%';
  58.     Open;
  59.   end;
  60. end;
  61.  
  62. An alternate way of referencing a parameter 
  63. (other then ParamByName) is params[TheParameterNumber].  
  64.  
  65. The way that this line:
  66.  
  67.     ParamByName('CompanyName').AsString := Edit1.Text + '%';
  68.  
  69. can be alternately written is:
  70.  
  71.     Params[0].AsString := Edit1.Text + '%';
  72.  
  73.  
  74. The trick to the wildcard is in the concatenating of the
  75. percentage sign at the end of the parameter.
  76.